package com.yc.jdbc;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.transaction.TransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.annotation.Resource;
import javax.sql.DataSource;

@Configuration // ==> beans.xml
@ComponentScan("com.yc.jdbc")
// 开启事务管理
@EnableTransactionManagement
public class JdbcConfig {

    @Bean  // @Component
    DataSource dataSource(){
        DriverManagerDataSource ds = new DriverManagerDataSource();
        ds.setDriverClassName("com.mysql.jdbc.Driver");
        ds.setUrl("jdbc:mysql:///bank");
        ds.setUsername("root");
        ds.setPassword("a");
        return ds;
    }

    @Bean
    // 1. 接口注入
    // 2. Spring @Bean 方法自动通过接口注入容器对象
    JdbcTemplate jdbcTemplate(DataSource dataSource){
        return new JdbcTemplate(dataSource);
    }

    @Resource
    DataSource dataSource;
    @Bean
    JdbcTemplate jdbc(){
        return new JdbcTemplate(dataSource);
    }

    // 事务管理器
    @Bean
    TransactionManager transactionManager(){
        DataSourceTransactionManager dataSourceTransactionManager
                = new DataSourceTransactionManager(dataSource);
        return dataSourceTransactionManager;
    }


}
